import { currentTime } from '../core/SimulationClock'
import { messageTransfer } from '../messaging/MessageTransfer'
import Product from './Product'
import BaseStation from './BaseStation'
import { addReadyProduct, getReadyProduct } from '../core/ReadyProducts'

class BufferNode extends BaseStation {
  capacity: number
  queue: Product[] = []
  isDispatchScheduled: boolean = false // 防止重复调度

  constructor(
    id: string,
    name: string,
    x: number,
    y: number,
    width = 100,
    height = 100,
    capacity: number
  ) {
    super(id, name, x, y, width, height)
    this.capacity = capacity
  }

  canReceiveProduct(): boolean {
    return this.queue.length < this.capacity
  }

  receiveReadyProduct(productId: string): void {
    if (this.queue.length < this.capacity) {
      const product = getReadyProduct(productId)
      if (product) {
        product.setFrom(this.id)
        this.onProductReceived(product)
      } else {
        console.log(`[${currentTime}] ❌ ${productId} 没有发现`)
      }
    } else {
      console.log(`[${currentTime}] ❌ ${this.name} 已经满了`)
    }
  }

  onProductReceived(product: Product): void {
    this.queue.push(product)
    messageTransfer('style', null, { targetId: this.id, style: { quantity: this.queue.length } })
    console.log(`[${currentTime}] 📥 ${product.id} 进入 ${this.name}`)

    messageTransfer('product', 'move', { targetId: this.id, productId: product.id })
    this.tryDispatchCurrentProduct()
  }

  // 触发调度但只允许一次调度同时运行
  public tryDispatchCurrentProduct(): void {
    for (const next of this.nextStations) {
      if (this.queue.length > 0 && next.canReceiveProduct(this.id, this.queue[0])) {
        const product = this.queue.shift()
        if (product) {
          addReadyProduct(product)
          next.receiveReadyProduct(product.id)
          messageTransfer('style', null, {
            targetId: this.id,
            style: { quantity: this.queue.length }
          })
        }
      }
    }
  }
}

export default BufferNode
